<template>
  <el-dialog
    v-model="dialogVisible"
    title="选择绘本"
    width="80%"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div class="book-selector">
      <!-- 搜索栏 -->
      <div class="search-bar mb-4">
        <el-row :gutter="16">
          <el-col :span="8">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索绘本集或绘本名称"
              clearable
              @input="handleSearch"
            >
              <template #prefix>
                <Icon icon="ep:search" />
              </template>
            </el-input>
          </el-col>
          <el-col :span="6">
            <el-select v-model="selectedLanguage" placeholder="选择语言" clearable @change="handleLanguageChange">
              <el-option label="英文" value="en" />
              <el-option label="中文" value="zh" />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-alert
              title="音频必须绑定到具体的绘本"
              type="info"
              :closable="false"
              show-icon
            />
          </el-col>
        </el-row>
      </div>

      <!-- 绘本选择 -->
      <div class="book-selection">
        <div class="section-title">选择绘本集</div>
        <el-select
          v-model="selectedBookSetId"
          placeholder="请先选择绘本集"
          clearable
          @change="handleBookSetSelect"
          class="w-full mb-4"
        >
          <el-option
            v-for="bookSet in filteredBookSets"
            :key="bookSet.id"
            :label="`${bookSet.title} (${bookSet.bookCount}本)`"
            :value="bookSet.id"
          />
        </el-select>

        <div v-if="selectedBookSetId" class="section-title">选择绘本</div>
        <el-scrollbar v-if="selectedBookSetId" height="300px">
          <div class="book-grid">
            <div
              v-for="book in filteredBooks"
              :key="book.id"
              class="book-item"
              :class="{ selected: selectedBookId === book.id }"
              @click="selectBook(book)"
            >
              <div class="book-cover">
                <img v-if="book.cover" :src="book.cover" alt="封面" />
                <div v-else class="no-cover">无封面</div>
              </div>
              <div class="book-info">
                <div class="book-title">{{ book.title }}</div>
                <div class="book-meta">
                  <span class="page-count">{{ book.pages }}页</span>
                </div>
              </div>
            </div>
          </div>
        </el-scrollbar>
      </div>

      <!-- 选中信息显示 -->
      <div v-if="selectedInfo" class="selected-info mt-4 p-3 bg-blue-50 rounded">
        <div class="text-sm text-blue-600">
          <Icon icon="ep:check" class="mr-1" />
          已选择: {{ selectedInfo }}
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm" :disabled="!hasSelection">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import * as AudioApi from '@/api/reading/audio'

interface BookSet {
  id: number
  title: string
  cover?: string
  bookCount: number
  language: string
}

interface Book {
  id: number
  title: string
  cover?: string
  pages: number
  bookSetId: number
}

interface SelectionResult {
  type: 'bookSet' | 'book'
  bookSetId?: number
  bookSetTitle?: string
  bookId?: number
  bookTitle?: string
}

const emit = defineEmits<{
  (e: 'confirm', result: SelectionResult): void
}>()

const dialogVisible = ref(false)
const searchKeyword = ref('')
const selectedLanguage = ref('')
const selectedBookSetId = ref<number>()
const selectedBookId = ref<number>()

const bookSets = ref<BookSet[]>([])
const books = ref<Book[]>([])

// 计算属性
const filteredBookSets = computed(() => {
  let result = bookSets.value
  
  if (selectedLanguage.value) {
    result = result.filter(item => item.language === selectedLanguage.value)
  }
  
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(item => 
      item.title.toLowerCase().includes(keyword)
    )
  }
  
  return result
})

const filteredBooks = computed(() => {
  let result = books.value
  
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(item => 
      item.title.toLowerCase().includes(keyword)
    )
  }
  
  return result
})

const selectedInfo = computed(() => {
  if (selectedBookId.value) {
    const book = books.value.find(item => item.id === selectedBookId.value)
    const bookSet = bookSets.value.find(item => item.id === selectedBookSetId.value)
    return book && bookSet ? `绘本: ${book.title} (来自: ${bookSet.title})` : ''
  }
  return ''
})

const hasSelection = computed(() => {
  // 只有选择了具体绘本才算有效选择
  return !!selectedBookId.value
})

// 方法
const open = () => {
  dialogVisible.value = true
  loadBookSets()
  resetSelection()
}

const handleClose = () => {
  dialogVisible.value = false
  resetSelection()
}

const resetSelection = () => {
  selectedBookSetId.value = undefined
  selectedBookId.value = undefined
  searchKeyword.value = ''
  selectedLanguage.value = ''
  books.value = []
}

const loadBookSets = async () => {
  try {
    const data = await AudioApi.getBookSetList()
    bookSets.value = data
  } catch (error) {
    console.error('加载绘本集失败:', error)
  }
}

const loadBooks = async (bookSetId: number) => {
  try {
    const data = await AudioApi.getBookList({ bookSetId })
    books.value = data
  } catch (error) {
    console.error('加载绘本失败:', error)
  }
}

const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理
}

const handleLanguageChange = () => {
  resetSelection()
}



const handleBookSetSelect = (bookSetId: number) => {
  selectedBookSetId.value = bookSetId
  selectedBookId.value = undefined
  if (bookSetId) {
    loadBooks(bookSetId)
  } else {
    books.value = []
  }
}

const selectBook = (book: Book) => {
  selectedBookId.value = book.id
}

const handleConfirm = () => {
  // 只允许选择具体的绘本
  if (selectedBookId.value) {
    const book = books.value.find(item => item.id === selectedBookId.value)
    const bookSet = bookSets.value.find(item => item.id === selectedBookSetId.value)
    emit('confirm', {
      type: 'book',
      bookSetId: selectedBookSetId.value,
      bookSetTitle: bookSet?.title,
      bookId: selectedBookId.value,
      bookTitle: book?.title
    })
    handleClose()
  }
}

defineExpose({
  open
})
</script>

<style scoped>
.book-selector {
  min-height: 500px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 12px;
  color: #303133;
}

.bookset-grid, .book-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
  padding: 8px;
}

.bookset-item, .book-item {
  border: 2px solid #e4e7ed;
  border-radius: 8px;
  padding: 12px;
  cursor: pointer;
  transition: all 0.3s;
}

.bookset-item:hover, .book-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
}

.bookset-item.selected, .book-item.selected {
  border-color: #409eff;
  background-color: #ecf5ff;
}

.bookset-cover, .book-cover {
  width: 100%;
  height: 120px;
  border-radius: 6px;
  overflow: hidden;
  margin-bottom: 8px;
}

.bookset-cover img, .book-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.no-cover {
  width: 100%;
  height: 100%;
  background-color: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  font-size: 12px;
}

.bookset-title, .book-title {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.bookset-meta, .book-meta {
  font-size: 12px;
  color: #909399;
  display: flex;
  justify-content: space-between;
}
</style>
